<template>
    <div>
        <div class="commonStyle nyContent">
            <div class="commonTit">网络管理</div>
            <a-radio-group v-model="currentTabName" buttonStyle="solid" @change="changeTab" style="margin: 5px 0 40px;" >
                <a-radio-button v-for="item in initTabList" :key="item.value" :value="item.value">
                    {{item.label}}
                </a-radio-button>
            </a-radio-group>
            <div v-if="currentTabName !== '3'">
                <div class="formSearch" style="float: right; position: relative; z-index: 999">
                    <a-form layout="inline" @keydown.native.enter.prevent="">
                        <a-form-item label=" ">
                            <a-input v-model="searchForm.searchKey" placeholder="请输入名称搜索"
                                     @keyup="formatEnterContent(searchForm.searchKey)"
                                     @blur="formatEnterContent(searchForm.searchKey)" style="width: 220px">
                                <a-icon slot="prefix" type="user" class="displayPre" />
                                <a-icon v-if="searchForm.searchKey" slot="suffix" type="close-circle" @click="emitEmpty(searchForm,searchForm.searchKey)" />
                            </a-input>
                        </a-form-item>
                        <a-button type="primary" @click="handleSubmit">查询</a-button>
                        <a-button style="margin-left:16px" @click="reStore">重置</a-button>
                    </a-form>
                </div>
                <div class="apply-title-btn-wrap" style="float: left">
                    <a-button type="primary" @click="showAddModal">新增</a-button>
                </div>
                <a-table :columns="commonColumns" :dataSource="tableListData" :rowKey="record => record.id"
                         :pagination="false" >
                <span slot="index" slot-scope="text, record, index">
                    {{ (searchForm.currentPage - 1) * searchForm.pageSize + index + 1 }}
                </span>
                    <span slot="enable" slot-scope="text"  :style="Number(text) !== 1?'':'color:green'">
                            {{ Number(text) === 1 ? '启用' : '禁用' }}
                        </span>
                    <span slot="operation" slot-scope="text" class="table-operation">
                         <a @click="showEditModal(text)" >编辑</a>
                         <a @click="enableNetConfigFun(text)"  v-if="currentTabName === '1'">{{ Number(text.enable) === 1 ? '禁用' : '启用' }}</a>
                         <a @click="delFun(text)" class="adel"  v-if="currentTabName !== '1'">删除</a>
                </span>
                </a-table>
                <Page :totalCount="searchForm.total" :currentPage="searchForm.currentPage"
                      :pageSize="searchForm.pageSize" @changePage="changePage" @changePageSize="changePageSize" />
            </div>
            <div class="syMsg"  v-if="currentTabName === '3'">
                <div class="syMsgTit">DNS配置</div>
                <div class="syMsgCot">
                    <a-form ref="form" :form="form2" class="onePageMsg"  style=" width: 100% !important;">
                        <a-form-item label="主 DNS 服务器：" v-bind="formStyle">
                            <a-input type="text" class="formWidth" v-decorator="[
                                        'preferDns',
                                        {
                                            rules: [{ required: false}, { validator: this.verify.validateIP.bind(this) }],
                                            getValueFromEvent: event => {
                                                return this.verify.formalIP(event,18)
                                            }
                                        }
                                    ]"/>
                        </a-form-item>
                        <a-form-item label="备 DNS 服务器：" v-bind="formStyle">
                            <a-input type="text"  class="formWidth" v-decorator="[
                                        'standbyDns',
                                        {
                                            rules: [{ required: false}, { validator: this.verify.validateIP.bind(this) }],
                                            getValueFromEvent: event => {
                                                return verify.formalIP(event)
                                            }
                                        }
                                    ]" />
                        </a-form-item>
                        <a-form-item label=" " v-bind="formStyle" class="noLabelAfter" >
                            <a-button type="primary" size="default" @click="saveApply">保存</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </div>
            <add-edit ref="addEdit" @init="init"/>
            <add-edit-route ref="addEditRoute" @init="init"/>
            <add-edit-strategy ref="addEditStrategy" @init="init"/>
        </div>
        <div class="spinBox" v-if="spinning">{{spinText}}</div>
    </div>
</template>

<script>
    import { mapState } from 'vuex'
    import verify from 'libs/verify'
    import Page from 'module/pagination'
    import Util from '@/libs/util'
    import addEditRoute from './addEditRoute'
    import addEdit from './addEdit'
    import addEditStrategy from './addEditStrategy'
    export default {
        name: 'networkSetting',
        components: {
            Page,
            addEditRoute,
            addEdit,
            addEditStrategy,
        },
        data () {
            return {
                form: this.$form.createForm (this),
                form2: this.$form.createForm (this),
                verify,
                spinning:false,
                spinText:'请稍后...',
                timer:null,
                currentTabName:'1',
                formStyle:{
                    labelCol: {span: 3},
                    wrapperCol: {span: 17}
                },
                initTabList:[{value:'1',label:'网络配置'},{value:'2',label:'路由配置'},{value:'3',label:'DNS设置'},{value:'4',label:'IP伪装策略'}],
                id:'0',
                commonColumns:[],
                columns: [
                    {title: '序号', key: 'index', width: '7%', align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: '网卡名称', dataIndex: 'internetAdapterName', key: 'internetAdapterName'},
                    {title: 'IPV4地址', dataIndex: 'ipv4', key: 'ipv4'},
                    {title: '子网掩码', dataIndex: 'mask', key: 'mask'},
                    {title: '默认网关', dataIndex: 'defautGateWay', key: 'defautGateWay'},
                    {title: '网卡状态', dataIndex: 'enable', key: 'enable', scopedSlots: {customRender: 'enable'}},
                    {title: '操作', key: 'operation', width: '13%', scopedSlots: {customRender: 'operation'}}
                ],
                tableListData:[],
                routeColumns: [
                    {title: '序号', key: 'index', width: '7%', align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: '目地IP', dataIndex: 'destIp', key: 'destIp'},
                    {title: '目地IP掩码', dataIndex: 'destMask', key: 'destMask'},
                    {title: '路由IP', dataIndex: 'gateWay', key: 'gateWay'},
                    {title: '操作', key: 'operation', width: '13%', scopedSlots: {customRender: 'operation'}}
                ],
                routeDataList:[],
                strategyColumns: [
                    {title: '序号', key: 'index', width: '7%', align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: '策略名称', dataIndex: 'strategyName', key: 'strategyName'},
                    {title: '源地址', dataIndex: 'ip', key: 'ip'},
                    {title: '伪装地址', dataIndex: 'adapterName', key: 'adapterName'},
                    {title: '操作', key: 'operation', width: '13%', scopedSlots: {customRender: 'operation'}}
                ],
                strategyDataList:[],
                searchForm: {
                    searchKey: '', //分应用名称
                    pageSize:10, //每页大小
                    currentPage: 1, //页码
                    total:100
                },
            }
        },
        computed: {
            ...mapState ({
                netWorkList: state => state.common.netWorkList,
            })
        },
        created () {
            if( this.currentTabName === '1'){
                this.commonColumns = this.columns
            }
            this.init()
            this.getNetWorkList()

        },
        methods: {
            getNetWorkList(){
                this.$get('/net/getInternetAdapterName').then(res => {
                    if (res.code === 0) {
                        this.$store.dispatch('setNetWorkList', res.data)
                    } else {
                        this.$message.error(res.message)
                    }
                }).catch(res => {
                    this.$message.error(res.message)
                })
            },
            /**
             * Function    : delFun
             * Description : 确定删除
             * Input       : 产品id
             * Return      : none
             */
            delFun (text) {
                let _this = this;
                let url = ''
                let params = {}
                let msg = ''
                let name = ''
                if( this.currentTabName === '1'){
                    url = ''
                }else if( this.currentTabName === '2'){
                    url = '/route/delRouteConfig'
                    params.destIp = text.destIp
                    params.destMask = text.destMask
                    params.gateWay = text.gateWay
                    msg = '路由'
                    name =  text.destIp
                }else if( this.currentTabName === '4'){
                    url = '/nat/delNatConfig'
                    msg = '伪装地址'
                    name =  text.ip
                    params.ip = text.ip
                    params.natIp = text.natIp
                }
                _this.$confirm({
                    title: `确定要删除 ${name} ${msg}?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        _this.$post(url, {ids:text.id}).then(res => {
                            if (res.code === 0) {
                                if(_this.tableListData.length === 1 && _this.searchForm.currentPage>1){
                                    _this.searchForm.currentPage = _this.searchForm.currentPage-1;
                                }
                                _this.init();
                                _this.$message.success(`删除  ${name} ${msg}成功！`);
                            } else {
                                _this.$message.error(res.message)
                            }
                        })
                    }
                })
            },
            init(){
                let _this = this
                let url = ''
                if( this.currentTabName === '1'){
                    url = '/net/queryNetConfig'
                }else if( this.currentTabName === '2'){
                    url = '/route/queryRouteConfig'
                }else if( this.currentTabName === '4'){
                    url = '/nat/queryNatConfig'
                }
                _this.$get (url,this.searchForm).then (res => {
                    if (res.code === 0) {
                        _this.tableListData = res.data.rows
                        _this.searchForm.total = res.data.total
                    } else {
                        _this.$message.error(res.message)
                    }
                })
            },
            getDnsConfigFun(){
                let _this = this
                _this.$get ('/dns/getDnsConfig').then (res => {
                    if (res.code === 0) {
                        _this.$nextTick(() => {
                            _this.$nextTick(() => {
                                _this.$nextTick(() => {
                                    _this.$nextTick(() => {
                                        _this.form2.setFieldsValue(
                                            _this.$pick(res.data, [
                                                'preferDns',
                                                'standbyDns'
                                            ])
                                        )
                                    })
                                })
                            })
                        })
                    } else {
                        _this.$message.error(res.message)
                    }
                })
            },
            /**
             * Function    : saveApply
             * Description : 保存
             * Input       : name
             * Return      : none
             */
            saveApply(e) {
                e.preventDefault()
                this.form2.validateFields((err, value) => {
                    if (!err) {
                        let _this =this
                        _this.$post ('/dns/setDnsConfig', value).then (res => {
                            if (res.code === 0) {
                                _this.$message.success (res.message)
                            } else {
                                _this.$message.error (res.message)
                            }
                        })
                    }
                })
            },
            /**
             * Function    : changeTab
             * Description : 切换tab页触发函数
             * Input       : name tab页名称
             * Return      : none
             */
            changeTab ( name ) {
                this.currentTabName = name.target.value
                if(this.currentTabName === '3'){
                    this.getDnsConfigFun()
                }else{
                    if( this.currentTabName === '1'){
                        this.commonColumns = this.columns
                    }else if( this.currentTabName === '2'){
                        this.commonColumns = this.routeColumns
                    }else if( this.currentTabName === '4'){
                        this.commonColumns = this.strategyColumns
                    }
                    this.searchForm.searchKey = ''
                    this.searchForm.currentPage = 1
                    this.init()
                }
                this.form.resetFields()

            },
            /**
             * Function    : changePage
             * Description : 切换页码
             * Input       :  val
             * Return      : none
             */
            changePage ( val ) {
                this.searchForm.currentPage = val
                this.init ()
            },

            /**
             * Function    : changePageSize
             * Description : 切换每页条数
             * Input       :  vm
             * Return      : none
             */
            changePageSize ( vm ) {
                this.searchForm.pageSize = vm
                this.searchForm.currentPage = 1
                this.init ()
            },
            updNetDns(){
                this.form2.validateFields((err, value) => {
                    if (!err) {
                        let _this =this
                        let para = [
                            {"id": _this.dnsList[0].id, "dns": value.mainIp},
                            {"id": _this.dnsList[1].id, "dns": value.beiIp}
                        ]
                        _this.$post ('api/networks/updNetDns', para).then (res => {
                            if (res.code === 0) {
                                _this.findNetDns()
                                _this.$message.success (res.message)
                            } else {
                                _this.$message.error (res.message)
                            }
                        })
                    }
                })
            },
            emitEmpty (partant,name) {
                this[partant][name] = ''
                this.init();
            },
            reStore () {
                this.searchForm.searchKey = ''
                this.searchForm.pageNo = 1
                this.init ()
            },
            /** 过滤输入框输入的特殊字符* */
            formatEnterContent (  partant, name,value ) {
                let a = Util.clearSpecialChart (value)
                this[ partant ][ name ] = a
            },
            /**
             * Function    : handleSubmit
             * Description : 查询按钮
             * Input       : none
             * Return      : none
             */
            handleSubmit () {
                this.searchForm.currentPage = 1
                this.init ()
            },
            showAddModal(){
                if( this.currentTabName === '1'){
                    this.$refs.addEdit.showAddModal()
                }else if( this.currentTabName === '2'){
                    this.$refs.addEditRoute.showAddModal()
                }else if( this.currentTabName === '4'){
                    this.$refs.addEditStrategy.showAddModal()
                }
            },
            showEditModal(text){
                if( this.currentTabName === '1'){
                    this.$refs.addEdit.showEdit(text)
                }else if( this.currentTabName === '2'){
                    this.$refs.addEditRoute.showEdit(text)
                }else if( this.currentTabName === '4'){
                    this.$refs.addEditStrategy.showEdit(text)
                }
            },
            enableNetConfigFun(text){
                let msg = '启用'
                let enable = 1
                if(text.enable === 1){
                    msg = '禁用'
                    enable = 0
                }
                this.$confirm ({
                    title: `确定${msg}${text.ipv4}吗?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        let _this =this
                        let prams = {
                            id:text.id,
                           /* internetAdapterName:text.internetAdapterName,*/
                            enable:enable,
                        }
                        _this.$post("/net/enableNetConfig", prams).then(res => {
                            if (res.code === 0) {
                                _this.$message.success (res.message)
                                _this.init ()
                            } else {
                                _this.$message.error(res.message)
                            }
                        })
                    }
                })
            }
        },
        destroyed() {}
    }
</script>
<style lang="less" scoped>
    .serialPortGroup{
        .ant-radio-button-wrapper{ border-radius: 8px !important;}
    }
</style>